import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xcite/core/utils/ali.dart';

import '../../core/models/private_chat_model.dart';
import '../../core/providers/private_chat_provider.dart';
import '../../core/providers/user_provider.dart';
import '../../core/utils/popup_helper.dart';
import '../../core/utils/toast_helper.dart';

class PrivateChatScreen extends ConsumerStatefulWidget {
  final String conversationId;
  final String? otherUserId;

  const PrivateChatScreen({
    super.key,
    required this.conversationId,
    this.otherUserId,
  });

  @override
  ConsumerState<PrivateChatScreen> createState() => _PrivateChatScreenState();
}

class _PrivateChatScreenState extends ConsumerState<PrivateChatScreen> {
  final TextEditingController _inputController = TextEditingController();
  final ScrollController _listController = ScrollController();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _markMessagesAsRead();
    });
  }

  @override
  void dispose() {
    _inputController.dispose();
    _listController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final currentUser = ref.watch(currentUserProvider);
    final conversation = ref
        .read(privateChatProvider.notifier)
        .getConversationById(widget.conversationId);
    final messagesAsync = ref.watch(
      conversationMessagesProvider(widget.conversationId),
    );

    if (currentUser == null || conversation == null) {
      return Scaffold(
        body: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/resources/common_bg_2.png'),
              fit: BoxFit.cover,
            ),
          ),
          child: Center(
            child: Text('Loading...').fontSize(16.sp).textColor(Colors.grey),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/resources/common_bg_2.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              _buildNavigationHeader(),
              Expanded(
                child: messagesAsync.when(
                  data:
                      (messages) => _buildChatContent(messages, currentUser.id),
                  loading:
                      () => Center(
                        child: CircularProgressIndicator(
                          color: Color(0xFFFFD700),
                        ),
                      ),
                  error:
                      (error, stack) => Center(
                        child: Text(
                          'Error loading messages',
                        ).fontSize(16.sp).textColor(Colors.grey),
                      ),
                ),
              ),
              _buildInputSection(currentUser),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildNavigationHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          Container(
            width: 30.w,
            height: 30.w,
            decoration: BoxDecoration(
              color: Colors.black,
              shape: BoxShape.circle,
            ),
            child:
                Icon(
                  Icons.arrow_back_ios_new,
                ).iconSize(16.sp).iconColor(Colors.white).center(),
          ).inkWell(onTap: () => GoRouter.of(context).pop()),

          Spacer(),

          Text(
            'Chat',
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.bold,
              color: Colors.black,
              fontFamily: 'PoetsenOne',
            ),
          ),

          Spacer(),

          Container(
            width: 30.w,
            height: 30.w,
            decoration: BoxDecoration(
              color: Colors.black,
              shape: BoxShape.circle,
            ),
            child:
                Icon(
                  AliIcons.iconReport,
                ).iconSize(22.sp).iconColor(Colors.white).center(),
          ).inkWell(onTap: _handleReportAction),
        ],
      ),
    );
  }

  Widget _buildChatContent(
    List<PrivateChatMessageEntity> messages,
    String currentUserId,
  ) {
    return ListView.builder(
      controller: _listController,
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      itemCount: messages.length,
      itemBuilder: (context, index) {
        final message = messages[index];
        final isFromCurrentUser = message.senderId == currentUserId;
        return _buildChatBubble(message, isFromCurrentUser);
      },
    );
  }

  Widget _buildChatBubble(
    PrivateChatMessageEntity message,
    bool isFromCurrentUser,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        children: [
          if (!isFromCurrentUser) ...[
            _buildUserAvatar(message.senderId),
            SizedBox(width: 12.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  if (message.messageType == PrivateChatMessageType.text)
                    _buildTextBubble(message.content, isFromCurrentUser)
                  else if (message.messageType == PrivateChatMessageType.image)
                    _buildImageBubble(message.content, isFromCurrentUser),
                ],
              ),
            ),
            SizedBox(width: 40.w),
          ] else ...[
            SizedBox(width: 40.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  if (message.messageType == PrivateChatMessageType.text)
                    _buildTextBubble(message.content, isFromCurrentUser)
                  else if (message.messageType == PrivateChatMessageType.image)
                    _buildImageBubble(message.content, isFromCurrentUser),
                ],
              ),
            ),
            SizedBox(width: 12.w),
            _buildUserAvatar(message.senderId),
          ],
        ],
      ),
    );
  }

  Widget _buildUserAvatar(String userId) {
    final userNotifier = ref.read(userProvider.notifier);
    final allUsers = userNotifier.getAllDefaultUsers();
    final user = allUsers.where((u) => u.id == userId).firstOrNull;

    return Container(
      width: 52.w,
      height: 52.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        image: DecorationImage(
          image: AssetImage(user?.avatar ?? 'assets/resources/avatar1.png'),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget _buildTextBubble(String content, bool isFromCurrentUser) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(29.r),
      ),
      padding:
          isFromCurrentUser
              ? EdgeInsets.only(left: 2.w, bottom: 2.w)
              : EdgeInsets.only(right: 2.w, bottom: 2.w),
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
        decoration: BoxDecoration(
          color: Color(0xFFFDF5E1),
          borderRadius: BorderRadius.circular(29.r),
          border: Border.all(color: Colors.black, width: 2.w),
        ),
        child: Text(
          content,
          style: TextStyle(fontSize: 14.sp, color: Colors.black),
        ),
      ),
    );
  }

  Widget _buildImageBubble(String imagePath, bool isFromCurrentUser) {
    return Container(
      width: 155.w,
      height: 155.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: Colors.black, width: 2.w),
        image: DecorationImage(image: AssetImage(imagePath), fit: BoxFit.cover),
      ),
    );
  }

  Widget _buildInputSection(dynamic currentUser) {
    return Container(
      margin: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Color(0xFFF5F5DC),
        borderRadius: BorderRadius.circular(25.r),
        border: Border.all(color: Colors.black, width: 3),
      ),
      child: SafeArea(
        top: false,
        child: Container(
          height: 56.h,
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Expanded(
                child: TextField(
                  controller: _inputController,
                  decoration: InputDecoration(
                    hintText: 'say something...',
                    hintStyle: TextStyle(
                      color: Colors.grey[600],
                      fontSize: 16.sp,
                    ),
                    border: InputBorder.none,
                    isDense: true,
                  ),
                  style: TextStyle(fontSize: 16.sp, color: Colors.black),
                  maxLines: null,
                  textInputAction: TextInputAction.done,
                  onChanged: (value) {
                    setState(() {});
                  },
                ),
              ),
              SizedBox(width: 12.w),
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Color(0xFFFFD700),
                  shape: BoxShape.circle,
                ),
                child:
                    Icon(
                      AliIcons.iconPhoto,
                    ).iconSize(22.sp).iconColor(Colors.white).center(),
              ).inkWell(onTap: () => _handleImageSelection(currentUser)),
              SizedBox(width: 8.w),
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Color(0xFFFFD700),
                  shape: BoxShape.circle,
                ),
                child:
                    Icon(
                      AliIcons.iconSend,
                    ).iconSize(22.sp).iconColor(Colors.white).center(),
              ).inkWell(
                onTap:
                    _inputController.text.trim().isNotEmpty
                        ? () => _handleTextSend(currentUser)
                        : null,
              ),
            ],
          ),
        ),
      ),
    );
  }

  void _markMessagesAsRead() async {
    final currentUser = ref.read(currentUserProvider);
    if (currentUser != null) {
      await ref
          .read(privateChatProvider.notifier)
          .markMessagesAsRead(
            conversationId: widget.conversationId,
            userId: currentUser.id,
          );
    }
  }

  void _handleReportAction() {
    PopupHelper.showReportDialog(
      context,
      onReportSubmitted: (reportType) async {
        if (mounted) {
          ToastHelper.success(
            'Report submitted successfully',
            context: context,
          );
          GoRouter.of(context).pop();
        }
      },
      onCancelPressed: () {},
    );
  }

  Future<void> _handleImageSelection(dynamic currentUser) async {
    try {
      final List<AssetEntity>? assets = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          themeColor: Color(0xFFFFD700),
        ),
      );

      if (assets != null && assets.isNotEmpty) {
        final file = await assets.first.file;
        if (file != null) {
          await _handleImageSend(currentUser, file.path);
        }
      }
    } catch (e) {
      if (mounted) {
        ToastHelper.error('Failed to select image', context: context);
      }
    }
  }

  Future<void> _handleTextSend(dynamic currentUser) async {
    final content = _inputController.text.trim();
    if (content.isEmpty) return;

    final conversation = ref
        .read(privateChatProvider.notifier)
        .getConversationById(widget.conversationId);
    if (conversation == null) return;

    final receiverId =
        conversation.participantOneId == currentUser.id
            ? conversation.participantTwoId
            : conversation.participantOneId;

    final success = await ref
        .read(privateChatProvider.notifier)
        .sendMessage(
          conversationId: widget.conversationId,
          senderId: currentUser.id,
          receiverId: receiverId,
          messageType: PrivateChatMessageType.text,
          content: content,
        );

    if (success) {
      _inputController.clear();
      _scrollToEnd();
    } else {
      if (mounted) {
        ToastHelper.error('Failed to send message', context: context);
      }
    }
  }

  Future<void> _handleImageSend(dynamic currentUser, String imagePath) async {
    final conversation = ref
        .read(privateChatProvider.notifier)
        .getConversationById(widget.conversationId);
    if (conversation == null) return;

    final receiverId =
        conversation.participantOneId == currentUser.id
            ? conversation.participantTwoId
            : conversation.participantOneId;

    final success = await ref
        .read(privateChatProvider.notifier)
        .sendMessage(
          conversationId: widget.conversationId,
          senderId: currentUser.id,
          receiverId: receiverId,
          messageType: PrivateChatMessageType.image,
          content: imagePath,
        );

    if (success) {
      _scrollToEnd();
      if (mounted) {
        ToastHelper.success('Image sent', context: context);
      }
    } else {
      if (mounted) {
        ToastHelper.error('Failed to send image', context: context);
      }
    }
  }

  void _scrollToEnd() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_listController.hasClients) {
        _listController.animateTo(
          _listController.position.maxScrollExtent,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }
}
